package com.licq.ldoc.support.bean;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.keyvalue.DefaultMapEntry;

public class DefaultKeyValue<K, V> extends AbstractKeyValue<K, V> {

	public DefaultKeyValue() {
		super(null, null);
	}
	
	public DefaultKeyValue(K key, V value) {
		super(key, value);
	}
	
	public DefaultKeyValue(KeyValue<K, V> keyValue) {
		super(keyValue.getKey(), keyValue.getValue());
	}
	
	public DefaultKeyValue(Entry<K, V> entry) {
		super(entry.getKey(), entry.getValue());
	}
	
	public K setKey(K key) {
		if (key == this) {
            throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a key.");
        }

        final K old = this.key;
        this.key = key;
        return old;
	}
	
	public V setValue(V value) {
        if (value == this) {
            throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a value.");
        }

        final V old = this.value;
        this.value = value;
        return old;
    }
	
	@SuppressWarnings("unchecked")
	public Map.Entry<K, V> toMapEntry() {
        return new DefaultMapEntry(key, value);
    }
	
	@SuppressWarnings("unchecked")
	public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!DefaultKeyValue.class.isInstance(obj)) {
            return false;
        }
        try {
	        DefaultKeyValue<K, V> other = (DefaultKeyValue<K, V>) obj;
	        return 
	            (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) 
	            && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()));
        } catch (Exception e) {
        	return false;
        }
    }
	
	public int hashCode() {
        return (getKey() == null ? 0 : getKey().hashCode()) 
        		^ (getValue() == null ? 0 : getValue().hashCode());
    }
	
}
